<template>
  <view>
    <uni-nav-bar
      :fixed="true"
      :border="false"
      color="#ffffff"
      background-color="#bf570c"
      left-icon="arrow-left"
      right-icon="home"
      title="命理精算"
      @clickLeft="backHistory"
      @clickRight="backHome"
    />
    <view class="container" v-if="hasOrder">
      <view class="top-title">
        <image
          class="top-title-img"
          src="@/static/images/synthesis/order/top-title.png"
          alt=""
        ></image>
      </view>
      <view class="goods-box">
        <image
          class="goods-img"
          src="@/static/images/synthesis/order/goods.png"
          alt=""
        ></image>
        <view class="goods-info">
          <view class="goods-info-left">
            <view class="goods-name">
              {{ goods.pname }}
            </view>
            <view class="goods-des">
              {{ goods.description }}
            </view>
          </view>
          <view class="goods-info-right">
            <view class="goods-price">
              <view class="price-current">
                <span class="price-unit">￥</span
                >{{ parseInt(goods.price) / 100 }}元
              </view>
              <view class="price-origin"
                >原价{{ parseInt(goods.originalPrice) / 100 }}元</view
              >
            </view>
          </view>
        </view>
      </view>
      <view class="purchase-btn-box">
        <image
          @click="open(goods)"
          class="purchase-btn"
          src="@/static/images/synthesis/order/purchase.png"
          alt=""
        ></image>
      </view>
      <view class="ad-tips-box">
        <img
          class="top-tips-img"
          src="@/static/images/synthesis/order/top-tips.png"
        />
      </view>
      <view class="ad-box">
        <img class="ad-box-bg" src="@/static/images/synthesis/order/sycy.png" />
        <view class="ad-box-btn-box" @click="open(goods)">
          <img
            class="ad-box-btn"
            src="@/static/images/synthesis/order/unlock.png"
          />
        </view>
      </view>
      <view class="ad-box">
        <img class="ad-box-bg" src="@/static/images/synthesis/order/hygq.png" />
        <view class="ad-box-btn-box" @click="open(goods)">
          <img
            class="ad-box-btn"
            src="@/static/images/synthesis/order/unlock.png"
          />
        </view>
      </view>
      <view class="ad-box">
        <img class="ad-box-bg" src="@/static/images/synthesis/order/jkfs.png" />
        <view class="ad-box-btn-box" @click="open(goods)">
          <img
            class="ad-box-btn"
            src="@/static/images/synthesis/order/unlock.png"
          />
        </view>
      </view>
      <view class="ad-box">
        <img class="ad-box-bg" src="@/static/images/synthesis/order/wlyn.png" />
        <view class="ad-box-btn-box" @click="open(goods)">
          <img
            class="ad-box-btn"
            src="@/static/images/synthesis/order/unlock.png"
          />
        </view>
      </view>
      <view class="ad-box">
        <img class="ad-box-bg" src="@/static/images/synthesis/order/hmjx.png" />
        <view class="ad-box-btn-box" @click="open(goods)">
          <img
            class="ad-box-btn"
            src="@/static/images/synthesis/order/unlock.png"
          />
        </view>
      </view>
      <view class="ad-box">
        <img class="ad-box-bg" src="@/static/images/synthesis/order/zwds.png" />
        <view class="ad-box-btn-box" @click="open(goods)">
          <img
            class="ad-box-btn"
            src="@/static/images/synthesis/order/unlock.png"
          />
        </view>
      </view>
      <view class="ad-tips-box">
        <img
          class="bottom-tips-img"
          src="@/static/images/synthesis/order/bottom-tips.png"
        />
      </view>
      <!-- 支付弹窗 -->
      <uni-popup
        ref="popup"
        type="center"
        :mask-click="false"
        mask-background-color="rgba(0,0,0,0.8)"
      >
        <view class="login-hit-box">
          <view class="pay-info-box">
            <view class="pay-tips"> 确认你的购买信息 </view>
            <view class="info-item-box">
              <view class="info-item">
                <view class="item-title">名称</view>
                <view class="item-content">{{ name }}</view>
              </view>
              <view class="info-item">
                <view class="item-title">内容</view>
                <view class="item-content">{{ goods.description }}</view>
              </view>
              <view class="info-item" v-if="goods.originalPrice">
                <view class="item-title">原价</view>
                <view class="item-content origin-price"
                  >{{ parseInt(goods.originalPrice) / 100 }}元</view
                >
              </view>
              <view class="info-item">
                <view class="item-title">限时特价</view>
                <view class="item-content"
                  >{{ parseInt(goods.price) / 100 }}元</view
                >
              </view>
            </view>
          </view>
          <view class="login-hit-btn" @click="confirm">
            <img
              class="login-hit-btn-img"
              src="@/static/images/synthesis/order/pay.png"
            />
          </view>
          <view class="login-cancel-btn" @click="close">
            <img
              class="login-cancel-btn-img"
              src="@/static/images/synthesis/order/cancel.png"
            />
          </view>
        </view>
      </uni-popup>
    </view>
    <drag-button :isDock="true" :existTabBar="true" />
    <teacher-button :isDock="true" :existTabBar="true" />
    <preferential-modal
      ref="pre"
      :info="goods"
      @apply="confirm('isActivity')"
    ></preferential-modal>
  </view>
</template>

<script>
import { getGoodsByIdApi } from "@/http/api";
import {
  createOrdersApi,
  getOrderInfoBySuboidApi,
  weixinH5PayApi,
  weixiJsPayApi,
} from "@/http/api";
import { hourPeriodsToString } from "@/utils/index";
import { wxAppId, appGoodsId } from "@/http/env.js";
export default {
  data() {
    return {
      env: "",
      hasOrder: false,
      name: "",
      sex: "",
      birthday: "",
      area: "",
      phone: "",
      goods: [],
      activityNum: 1,
    };
  },
  onBackPress(options) {
    if (this.activityNum < 1) {
      this.$refs.pre.open();
      this.activityNum++;
      return true;
    }
    return false;
  },
  beforeDestroy() {
    // 在组件销毁前，移除 popstate 事件监听
    window.removeEventListener("popstate", this.onPopState);
  },

  mounted() {
    window.history.pushState(null, null, window.location.href);
    window.addEventListener("popstate", this.onPopState);

    uni.showLoading({
      title: "加载中",
    });
    // 查询商品信息
    getGoodsByIdApi({ pid: appGoodsId }).then((res) => {
      if (res.code === 200) {
        this.goods = res.data;
        uni.hideLoading();
        // 判断是否有活动价弹窗
        if (this.goods.isActivity == "1") {
          this.activityNum = 0;
        } else {
          this.activityNum = 1;
        }
        this.hasOrder = true;
      } else {
        uni.showToast({
          title: "商品查询失败",
          icon: "none",
        });
      }
    });
    let query = this.$route.query;
    this.name = query.username;
    this.sex = query.sex;
    this.birthday = query.birthday;
    this.solartime = query.solartime;
    this.area = query.area;
    this.phone = query.phone;

    const urlParams = new URLSearchParams(window.location.search);
    const code = urlParams.get("code");
    console.log("code");
    if (code) {
      const oid = urlParams.get("oid");
      // 将 code 发送给后端，获取支付参数
      console.log("oid");
      weixiJsPayApi({
        code: code,
        oid: oid,
      }).then((res) => {
        if (res.code === 200) {
          console.log(res.data);
          this.wxpay(res.data);
        }
      });
    }
  },
  methods: {
    // 环境判断
    getEnvFn() {
      var ua = window.navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return "weixin";
      } else if (/(iPhone|iPad|iPod|iOS)/i.test(window.navigator.userAgent)) {
        //判断iPhone|iPad|iPod|iOS
        return "iPhone";
      } else if (/(Android)/i.test(window.navigator.userAgent)) {
        //判断Android
        return "Android";
      } else {
        //pc
        return "pc";
      }
    },
    backHome() {
      uni.navigateTo({
        url: "/pages/synthesis/synthesis",
      });
    },
    backHistory() {
      if (this.activityNum < 1) {
        this.$refs.pre.open();
        this.activityNum++;
      } else {
        uni.navigateTo({
          url: "/pages/synthesis/synthesis",
        });
      }
    },
    onPopState(e) {
      if (this.activityNum < 1) {
        this.$refs.pre.open();
        this.activityNum++;
        window.history.pushState(null, null, window.location.href);
      } else {
        window.removeEventListener("popstate", this.onPopState);
        uni.navigateTo({
          url: "/pages/synthesis/synthesis",
        });
      }
    },
    open(item) {
      this.$refs.popup.open("center");
    },
    close() {
      if (this.activityNum < 1) {
        this.$refs.pre.open();
        this.activityNum++;
        return;
      }
      this.$refs.popup.close();
    },
    // 订单确认
    confirm(type) {
      // 创建新订单
      createOrdersApi({
        username: this.name,
        sex: this.sex,
        birthday: this.birthday,
        solartime: this.solartime,
        area: this.area,
        calculatePhone: this.phone,
        orderType: 1, // 1三合一  2姓名测算 3姻缘
        payType: 1, // 1微信  2支付宝
        pids: [appGoodsId],
        isActivity: type == "isActivity" ? 1 : 0,
        subChannelCode: uni.getStorageSync("sub"),
      }).then((res) => {
        if (res.code === 200) {
          this.pay(res.orderList[0].oid);
        } else {
          uni.showToast({
            title: res.msg,
            icon: "none",
          });
        }
      });
    },
    // 支付
    pay(oid) {
      if (oid == "" || oid == undefined || oid == null) {
        uni.showToast({
          title: "订单编号不存在",
          icon: "none",
        });
        return;
      }
      this.env = this.getEnvFn();
      let appId = wxAppId;
      let origin = window.location.origin;
      let scope = "snsapi_base";
      let pathName = window.location.pathname.split("/")[1];
      let baseUrl = pathName != "" ? `${origin}/${pathName}` : origin;

      let redirectUri = encodeURIComponent(
        `${baseUrl}/synthesis/synthesisOrder/synthesisGetCode?oid=${oid}`
      );
      window.location.replace(
        `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
      );
      // H5支付环境
      // if (this.env == 'iPhone' || this.env == 'Android') {
      //   // 微信
      //   weixinH5PayApi({
      //     h5ScenceType: this.env == 'iPhone' ? 'iOS' : 'Android',
      //     oid: oid
      //   }).then(res => {
      //     if(res.code === 200) {
      //       let redirectUri = encodeURIComponent(`${baseUrl}/pages/synthesis/synthesisResult/index?oid=${oid}`)
      //       window.location.href = `${res.h5_url}&redirect_url=${redirectUri}`
      //     }
      //   })
      // }else{

      // }
    },

    wxpay(data) {
      var ua = navigator.userAgent.toLowerCase();

      var isWeixin = ua.indexOf("micromessenger") != -1;

      if (isWeixin) {
        if (typeof WeixinJSBridge == "undefined") {
          if (document.addEventListener) {
            document.addEventListener(
              "WeixinJSBridgeReady",

              onBridgeReady,

              false
            );
          } else if (document.attachEvent) {
            document.attachEvent("WeixinJSBridgeReady", onBridgeReady);

            document.attachEvent("onWeixinJSBridgeReady", onBridgeReady);
          }
        } else {
          this.onBridgeReady(data);
        }
      } else {
        // this.goLoginPage (pay_params)
      }
    },

    onBridgeReady(params) {
      const pay_params = params;

      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",

        {
          appId: pay_params.appId, //公众号名称，由商户传入

          timeStamp: pay_params.timeStamp, //时间戳，自1970年以来的秒数

          nonceStr: pay_params.nonceStr, //随机串

          package: pay_params.package,

          signType: pay_params.signType, //微信签名方式：

          paySign: pay_params.paySign, //微信签名
        },

        function (res) {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            Toast.success("支付成功！");
          }
        }
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  background: url("@/static/images/synthesis/order/bg.png") no-repeat;
  background-size: 100%;
  padding: 18rpx 0 36rpx;
  .top-title {
    width: 100%;
    display: flex;
    justify-content: center;
    margin: 88rpx 0 28rpx;
  }
  .top-title-img {
    width: 489rpx;
    height: 36rpx;
  }
  .goods-box {
    background: url("@/static/images/synthesis/order/goods-box.png") no-repeat;
    background-size: 100% 100%;
    width: 702rpx;
    height: 1098rpx;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    align-items: center;
    .goods-img {
      width: 549rpx;
      height: 627rpx;
      margin: 68rpx 0 57rpx;
    }
    .goods-info {
      display: flex;
      flex-direction: row;
      align-items: center;
      width: 549rpx;
      .goods-info-left {
        .goods-name {
          font-size: 32rpx;
          font-weight: bold;
          margin-bottom: 21rpx;
        }
      }
      .goods-info-right {
        .goods-price {
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          white-space: nowrap;
          .price-current {
            color: #bb2800;
            font-weight: bold;
            font-size: 54rpx;
            .price-unit {
              font-size: 45rpx;
            }
          }
          .price-origin {
            font-size: 32rpx;
            color: #646464;
            text-decoration: line-through;
            white-space: nowrap;
          }
        }
      }
    }
  }
  .purchase-btn-box {
    width: 100%;
    display: flex;
    justify-content: center;
    .purchase-btn {
      width: 640rpx;
      height: 80rpx;
      animation-name: scaleDraw;
      animation-timing-function: ease-in-out;
      animation-iteration-count: infinite;
      animation-duration: 0.5s;
    }
  }
  .ad-tips-box {
    width: 100%;
    text-align: center;
    margin-top: 58rpx;
    .top-tips-img {
      width: 326rpx;
    }
    .bottom-tips-img {
      width: 505rpx;
    }
  }
  .ad-title-box {
    width: 100%;
    margin-top: 26rpx;
    text-align: center;
    .ad-title-img {
      width: 374rpx;
    }
  }
  .ad-box {
    width: 100%;
    text-align: center;
    position: relative;
    margin-top: 46rpx;
    .ad-box-bg {
      width: 635rpx;
    }
    .ad-box-btn-box {
      position: absolute;
      width: 100%;
      display: flex;
      justify-content: center;
      bottom: 70rpx;
      animation-name: scaleDraw;
      animation-timing-function: ease-in-out;
      animation-iteration-count: infinite;
      animation-duration: 0.5s;
    }
    .ad-box-btn {
      width: 263rpx;
    }
  }
}

.login-hit-box {
  width: 100%;
  margin: auto;
  box-sizing: border-box;
  position: relative;
}
.login-hit-close {
  position: absolute;
  right: 0;
  top: 0;
  width: 80rpx;
  height: 80rpx;
  cursor: pointer;
  z-index: 99;
}
.login-hit-img {
  width: 100%;
  margin-bottom: 56rpx;
}
.login-hit-btn {
  width: 640rpx;
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}
.login-hit-btn-img {
  width: 100%;
  display: block;
}
.login-cancel-btn {
  width: 640rpx;
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 40rpx;
}
.login-cancel-btn-img {
  width: 123rpx;
  height: 40rpx;
}

.pay-info-box {
  width: 645rpx;
  height: 353rpx;
  background: url("@/static/images/synthesis/index/content-bg.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  box-sizing: border-box;
  margin-bottom: 47rpx;
  position: relative;
  ::v-deep .label-text {
    font-size: 28rpx;
  }
  ::v-deep .uni-forms-item__inner {
    padding-bottom: 6rpx;
  }
  ::v-deep .uni-easyinput__content-input {
    padding-left: 0px !important;
  }
}
.info-item-box {
  width: 100%;
  padding: 50rpx 30rpx 30rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: space-evenly;
  height: 100%;
}
.pay-info-item {
  height: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
}
.info-item {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  justify-content: center;
  width: 100%;
}
.item-title {
  width: 140rpx;
  font-size: 28rpx;
  color: #666666;
  flex-shrink: 0;
}
.item-content {
  width: 320rpx;
  font-size: 28rpx;
  color: #333;
  flex-grow: 1;
}
.origin-price {
  text-decoration: line-through;
}
.pay-tips {
  position: absolute;
  top: 0rpx;
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
  color: #fff;
}
.has {
  filter: grayscale(100%);
}
</style>
